package com.atguigu.chapter08;

import com.atguigu.bean.LoginEvent;
import com.atguigu.util.AtguiguUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/7/23 9:14
 */
public class Flink05_High_Project_Login {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        // 创建WatermarkStrategy
        WatermarkStrategy<LoginEvent> wms = WatermarkStrategy
            .<LoginEvent>forBoundedOutOfOrderness(Duration.ofSeconds(20))
            .withTimestampAssigner(new SerializableTimestampAssigner<LoginEvent>() {
                @Override
                public long extractTimestamp(LoginEvent element, long recordTimestamp) {
                    return element.getEventTime();
                }
            });
    
        env
            .readTextFile("input/LoginLog.csv")
            .map(line -> {
                String[] data = line.split(",");
                return new LoginEvent(Long.valueOf(data[0]),
                                      data[1],
                                      data[2],
                                      Long.parseLong(data[3]) * 1000L);
            })
            .assignTimestampsAndWatermarks(wms)
            .keyBy(LoginEvent::getUserId)
            .countWindow(2, 1)
            .process(new ProcessWindowFunction<LoginEvent, String, Long, GlobalWindow>() {
                @Override
                public void process(Long key,
                                    Context context,
                                    Iterable<LoginEvent> elements,
                                    Collector<String> out) throws Exception {
                    // elements 个数: 最多是2
                    List<LoginEvent> eventList = AtguiguUtil.toList(elements);
                    if (eventList.size() == 2) {
                        LoginEvent event1 = eventList.get(0);
                        LoginEvent event2 = eventList.get(1);
                    
                        String type1 = event1.getEventType();
                        String type2 = event2.getEventType();
                    
                        Long ts1 = event1.getEventTime() / 1000;
                        Long ts2 = event2.getEventTime() / 1000;
                    
                        if ("fail".equals(type1) && "fail".equals(type2) && Math.abs(ts1 - ts2) <= 2) {
                            out.collect(key + " 正在恶意登录....");
                        }
                    }
                }
            })
            .print();
    
        env.execute();
    
    }
}
